package vi.org.rongcloud19test.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.Image;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.SpannableString;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;

import java.util.ArrayList;

import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import io.rong.message.TextMessage;
import vi.org.rongcloud19test.R;
import vi.org.rongcloud19test.adapter.ConversationAdapter;
import vi.org.rongcloud19test.utils.Constants;
import vi.org.rongcloud19test.utils.emoji.ParseEmojiMsgUtil;
import vi.org.rongcloud19test.utils.emoji.SelectFaceHelper;

/**
 * Created by Vicky on 2015/11/19.
 * RongCloud19Test
 * contact way: 317461087@qq.com
 */
public class ConversationActivity extends FragmentActivity implements View.OnClickListener{

    //括号内融云自己的单聊界面(
    //    String mTargetId,mTargetIds;
        /**
         * 会话类型
         */
    //    private Conversation.ConversationType mConversationType;
    //)

    //components
    private EditText mContent;
    private Button mSendBtn;
    private ImageButton mFunctionBtn,mEmoji;
    private ListView mListView;
    private View mFaceToolView;

    //conversation listview content
    public ConversationAdapter mAdapter;
    private ArrayList<Message> mMessageList;
    private String targetId;

    //emoji signals are visible or not
    private boolean isVisbilityFace = false;
    private SelectFaceHelper mFaceHelper;

    //broadcast receiver
    private PrivateMessageReceiver privateMessageReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_conversation);
        /*Intent intent = getIntent();
        getIntentDate(intent);*/

        mMessageList = new ArrayList<Message>();
        targetId = getIntent().getExtras().getString("targetId");
        mContent = (EditText)findViewById(R.id.send_content);
        mSendBtn = (Button)findViewById(R.id.send_btn);
        mListView = (ListView)findViewById(R.id.chatlist);
        mEmoji = (ImageButton)findViewById(R.id.emoji);
        mFaceToolView = (View)findViewById(R.id.send_msg_tool);
        mFunctionBtn = (ImageButton)findViewById(R.id.multi_function_btn);
        mSendBtn.setOnClickListener(this);
        mFunctionBtn.setOnClickListener(this);
        //emoji表情的使用，设置点击事件，在点击文本框时隐藏表情列表
        mEmoji.setOnClickListener(this);
        mContent.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                isVisbilityFace = false;
                mFaceToolView.setVisibility(View.GONE);
                return false;
            }
        });
        mAdapter = new ConversationAdapter(this,mMessageList,getIntent().getExtras().getString("portrait"));
        mListView.setAdapter(mAdapter);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId())
        {
            case R.id.send_btn:
                sendMsg();
                break;
            case R.id.multi_function_btn:

                break;
            case R.id.emoji:
                if (null == mFaceHelper) {
                    //在SelectFaceHelper中做一系列表情的初始化，填充表情列表数据等操作
                    mFaceHelper = new SelectFaceHelper(ConversationActivity.this, mFaceToolView);
                    //点击表情后触发mOnFaceOperatorListener
                    mFaceHelper.setFaceOpreateListener(mOnFaceOprateListener);
                }
                if (isVisbilityFace) {
                    //如果表情框可见时点击了表情按钮，则收回表情框
                    isVisbilityFace = false;
                    mFaceToolView.setVisibility(View.GONE);
                } else {
                    isVisbilityFace = true;
                    mFaceToolView.setVisibility(View.VISIBLE);
                    //显示表情框的同时隐藏软键盘
                    hideInputManager(ConversationActivity.this);
                }
                break;
        }
    }

    SelectFaceHelper.OnFaceOprateListener mOnFaceOprateListener = new SelectFaceHelper.OnFaceOprateListener() {
        @Override
        public void onFaceSelected(SpannableString spanEmojiStr) {
            if (null != spanEmojiStr) {
                //spanEmojiStr就是点击的表情，以str的形式存在
                mContent.append(spanEmojiStr);
            }
        }

        @Override
        public void onFaceDeleted() {
            int selection = mContent.getSelectionStart();
            String text = mContent.getText().toString();
            if (selection > 0) {
                String text2 = text.substring(selection - 1);
                if ("]".equals(text2)) {
                    int start = text.lastIndexOf("[");
                    int end = selection;
                    mContent.getText().delete(start, end);
                    return;
                }
                mContent.getText().delete(selection - 1, selection);
            }
        }

    };
    @Override
    protected void onResume() {
        super.onResume();
        privateMessageReceiver = new PrivateMessageReceiver();
        IntentFilter intentFilter = new IntentFilter(Constants.PRIVATE_MSG_RECEIVER);
        registerReceiver(privateMessageReceiver, intentFilter);
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(privateMessageReceiver);
    }
    // 隐藏软键盘
    public void hideInputManager(Context ct) {
        try {
            ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(((Activity) ct)
                    .getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        } catch (Exception e) {
            Log.e("conversationAc", "hideInputManager Catch error,skip it!", e);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    public class PrivateMessageReceiver extends BroadcastReceiver
    {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Constants.PRIVATE_MSG_RECEIVER)) {
                Message message = (Message)intent.getExtras().get(Constants.PRIVATE_MSG_INTENT);
                mMessageList.add(message);
                mAdapter.notifyDataSetChanged();
            }
        }
    }

    private void sendMsg()
    {
        final String msgStr = ParseEmojiMsgUtil.convertToMsg(mContent.getText(), ConversationActivity.this);
        if(null != msgStr && !msgStr.equals(""))
        {
            /**
             * 发送消息。
             *
             * @param type        会话类型。
             * @param targetId    目标 Id。根据不同的 conversationType，可能是用户 Id、讨论组 Id、群组 Id 或聊天室 Id。
             * @param content     消息内容。
             * @param pushContent push 时提示内容，为空时提示文本内容。
             * @param callback    发送消息的回调。
             * @return
             */
            RongIM.getInstance().getRongIMClient().sendMessage(Conversation.ConversationType.PRIVATE, targetId, TextMessage.obtain(msgStr)
                    , "","", new RongIMClient.SendMessageCallback() {
                @Override
                public void onError(Integer messageId, RongIMClient.ErrorCode e) {
                    Log.e("ConversationAc:","msg send error");
                }

                @Override
                public void onSuccess(Integer integer) {
                    Log.e("ConversationAc:", "msg send success");
                    Message message = new Message();
                    message.setContent(TextMessage.obtain(msgStr));
                    message.setMessageDirection(Message.MessageDirection.SEND);
                    Log.i("targetId",""+targetId);
                    message.setTargetId(targetId);
                    message.setSenderUserId(Constants.user.getUserId());
                    message.setConversationType(Conversation.ConversationType.PRIVATE);
                    mMessageList.add(message);
                    mAdapter.notifyDataSetChanged();
                }
            });
            mContent.setText("");
        }
        else {
            Log.e("ConversationAc","msg content is null");
        }
    }

    @Override
    public void onBackPressed() {
        if (isVisbilityFace) {// 好吧,隐藏表情菜单再退出
            isVisbilityFace = false;
            mFaceToolView.setVisibility(View.GONE);
            return;
        }
        finish();
//        super.onBackPressed();
    }

    //官方单聊intent地址
    /**
     * 展示如何从 Intent 中得到 融云会话页面传递的 Uri
     */
    /*private void getIntentDate(Intent intent) {

        mTargetId = intent.getData().getQueryParameter("targetId");
        mTargetIds = intent.getData().getQueryParameter("targetIds");
        //intent.getData().getLastPathSegment();//获得当前会话类型
//        mConversationType = Conversation.ConversationType.valueOf(intent.getData().getLastPathSegment().toUpperCase(Locale.getDefault()));
        mConversationType = Conversation.ConversationType.PRIVATE;
        enterFragment(mConversationType, mTargetId);
    }*/

    /**
     * 加载会话页面 ConversationFragment
     *
     * @param mConversationType 会话类型
     * @param mTargetId 目标 Id
     */
    /*private void enterFragment(Conversation.ConversationType mConversationType, String mTargetId) {

        ConversationFragment fragment = (ConversationFragment) getSupportFragmentManager().findFragmentById(R.id.conversation);

        Uri uri = Uri.parse("rong://" + getApplicationInfo().packageName).buildUpon()
                .appendPath("conversation").appendPath(mConversationType.getName().toLowerCase())
                .appendQueryParameter("targetId", mTargetId).build();
        fragment.setUri(uri);
    }*/
}
